#!/usr/bin/evn python
# -*- coding: utf-8 -*-

import os

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

import json
from bson import json_util
from bson.objectid import ObjectId

import pymongo
from markdown2 import markdown
from jdmz import settings as mongo_settings

from utils import get_pagination

from tornado.options import define, options
define('port', default=8000, help="run on the given port", type=int)


class Application(tornado.web.Application):
    def __init__(self):
        self.handlers = handlers

        settings = dict(
            template_path = os.path.join(os.path.dirname(__file__), 'templates'),
            static_path = os.path.join(os.path.dirname(__file__), 'static'),
            debug = True
        )

        client = pymongo.MongoClient(mongo_settings.MONGODB_SERVER, mongo_settings.MONGODB_PORT)
        self.db = client[mongo_settings.MONGODB_DB]

        tornado.web.Application.__init__(self, self.handlers, **settings)

class BaseHandler(tornado.web.RequestHandler):
    @property
    def db(self):
        return self.application.db

    @property
    def settings(self):
        return self.application.settings
    
    def get_pagination(self, count, limit=0):
        p = self.get_argument('p', '1')
        offset = limit*(int(p)-1)
        pagination = get_pagination(count, limit, int(p))
        return limit, offset, pagination


class HomeHandler(BaseHandler):
    def get(self):
        photos = self.db.meizi.find()

        self.render("index.html", photos=photos)


class AboutHandler(BaseHandler):
    def get(self):
        about_file = os.path.join(self.settings['template_path'], 'md/about.md')
        with open(about_file) as f:
            md = f.read()
        self.render("about.html", content=markdown(md))


#######################################
#          API                        #
#######################################
class MeizisHandler(BaseHandler):
    def get(self):
        meizis = self.db.meizi.find()
        self.set_header('Content-Type', 'application/json')
        self.write(json.dumps(list(meizis), default=json_util.default))


class MeiziHandler(BaseHandler):
    def get(self, id):
        meizi = self.db.meizi.find_one({"_id": ObjectId(str(id))})
        self.set_header('Content-Type', 'application/json')
        self.write(json.dumps((meizi), default=json_util.default))


handlers = [
    (r'/', HomeHandler),
    (r'/index', HomeHandler),
    (r'/about', AboutHandler),
    ## API
    (r'/api/v1/meizis', MeizisHandler),
    (r'/api/v1/meizi/(.*)', MeiziHandler)
]



if __name__ == '__main__':
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()